﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class caltaxil : System.Web.UI.UserControl
{
    protected static string msg;
    protected static string PAadd;
    protected static string AAadd;
    protected static string report;
    protected void Page_Load(object sender, EventArgs e)
    {
        setPage();
        PAadd = ""; // Pick Up Add.
        AAadd = ""; // Arrive Add.
        //Session["PAadd"] = PAadd;
        //Session["AAadd"] = AAadd;
        //Session["PACity"] = 1;
        //Session["PATown"] = "";
        if (Session["message"] != null)
        {
            Label1.Text = Session["message"].ToString();
        }
    }

    protected void setMemberAddress(bool st)
    {
        string query = "";
        DataSet ds = null;

        //if (ds != null && ds.Tables[0].Rows.Count > 0)
        //{
        this.lbl_customer.Text = "";
        this.lbl_customer.Text += Profile.Street + " sk, ";
        this.lbl_customer.Text += "No : " + Profile.No + ", ";
        this.lbl_customer.Text += Profile.Vicinity + " ";
        if (st)
        {
            this.txt_PAadd.Text = this.lbl_customer.Text; // !!!!
        }
        query = "SELECT * FROM [taxi].[dbo].[City] WHERE CityID = " + Profile.City;
        ds = DBClass.Default.SelectCommand(query);
        this.lbl_customer.Text += ds.Tables[0].Rows[0]["Name"] + "/";

        if (st)
        {
            this.drp_PAcity.SelectedValue = Profile.City.ToString(); // !!!!
            //this.drp_PAcity.SelectedItem.Text = ds.Tables[0].Rows[0]["Name"].ToString().Trim(); // !!!!
        Session["SCity"] = Profile.City.ToString();
        drp_PAtown.DataBind();
        drp_AAtown.DataBind();
        }
        

        query = "SELECT * FROM [taxi].[dbo].[Town] WHERE CityID = "+ Profile.City +" AND TownID = " + Profile.Town;
        ds = DBClass.Default.SelectCommand(query);
        this.lbl_customer.Text += ds.Tables[0].Rows[0]["Name"];
        if (st)
        {
            this.drp_PAtown.SelectedValue = Profile.Town.ToString();// !!!!
            //this.drp_PAtown.SelectedItem.Text = ds.Tables[0].Rows[0]["Name"].ToString().Trim(); // !!!!
        }



        //}
        //else
        //{
        //    // ERROR
        //    this.lbl_customer.Text = "No address found";
        //}
    }
        
    protected void setPage()
    {
        //int ut = 3;
        //if (Session["UserType"] != null)
        //{
        //    ut = (int)Session["UserType"];
        //}

        if (!Page.User.Identity.IsAuthenticated)
        {
            this.lbl_customer.Visible = false;
            this.Button2.Visible = false;
            //Session["SCity"] = 1;
            //this.drp_AAtown.DataBind();
        }
        else
        {
            this.lbl_customer.Visible = true;
            this.Button2.Visible = true;
            setMemberAddress(false);
        }
    }

    protected int selectLeastWorked(DataView ds)
    {
        int taxiID = 0;
        if (ds.Table.Rows.Count > 0)
        {
            taxiID = (int)ds.Table.Rows[0]["ID"];
            DateTime wrk = (DateTime)ds.Table.Rows[0]["CustomerArriveTime"];

            foreach (DataRow theRow in ds.Table.Rows)
            {

                if (wrk < (DateTime)theRow["CustomerArriveTime"])
                {
                    taxiID = (int)theRow["ID"];
                }
            }
        }
        return taxiID;
    }

    protected void sendTaxi(int taxiID, string PAadd, string AAadd)     
    {
        double _KmPrice = 0;
        int _DailyKm = 0;
        int _TotalKm = 0;
        double _Revenue = 0;
        DateTime _CustomerArriveTime = new DateTime();
        int _Km = 0;
        int _Time = 0;

        if (taxiID == 0)
        {
            Session["message"] = "Sorry there is not any available taxi for now";
            DBClass.Default.addLog(Profile.UserName, "send-taxi-fail", "no taxi", System.DateTime.Now);
            Response.Redirect("calltaxi.aspx");

        }
        else
        {

            string query = "SELECT * FROM [taxi].[dbo].[Taxi] WHERE ID =" + taxiID.ToString(); //  GET SELECTED TAXI
            DataSet ds = DBClass.Default.SelectCommand(query);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                _CustomerArriveTime = (DateTime)ds.Tables[0].Rows[0]["CustomerArriveTime"];
                _DailyKm = (int)ds.Tables[0].Rows[0][2];
                _TotalKm = (int)ds.Tables[0].Rows[0][3];
                _Revenue = (double)ds.Tables[0].Rows[0]["Revenue"]; // total
            }

            ds.Clear();
            query = "SELECT * FROM [taxi].[dbo].[Configuration]"; // GET KM PRICE
            ds = DBClass.Default.SelectCommand(query);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                _KmPrice = (double)ds.Tables[0].Rows[0]["KmPrice"];
            }

            ds.Clear();
            string w1;
            string w2;
            if (int.Parse(PAadd) < int.Parse(AAadd))
            {
                w1 = PAadd;
                w2 = AAadd;
            }
            else
            {
                w2 = PAadd;
                w1 = AAadd;
            }
            query = "SELECT * FROM [taxi].[dbo].[Way] WHERE Way1=" + w1 + " AND Way2=" + w2;
            ds = DBClass.Default.SelectCommand(query);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                _Km = (int)ds.Tables[0].Rows[0][2];
                _Time = (int)ds.Tables[0].Rows[0][3];
            }

            _CustomerArriveTime = _CustomerArriveTime.AddMinutes(_Km); // _Time olacak
            _DailyKm += _Km;
            _TotalKm += _Km;
            _Revenue += _Km * _KmPrice;

            query = "UPDATE [taxi].[dbo].[Taxi] SET CustomerArriveTime='" + _CustomerArriveTime.ToString("dd.MM.yyyy") + "',DailyKm=" + _DailyKm.ToString() + ",TotalKm=" + _TotalKm.ToString() + ",Revenue=" + _Revenue.ToString().Replace(",",".") + ",Available='busy',CurrentLocation=" + AAadd + " WHERE ID=" + taxiID;
            
            
            if (DBClass.Default.UpdateCommand(query))
            {
                
                DBClass.Default.addLog(Profile.UserName, "send-taxi-ok", report, System.DateTime.Now);
                Session["message"] = "Taxi is sending to address. Thanksfor using TCC";
               Response.Redirect("calltaxi.aspx");

            }
            else
            {
                DBClass.Default.addLog(Profile.UserName, "send-taxi-fail", report, System.DateTime.Now);
                Session["message"] = "Sorry. An error is occurred.\nPlease use contact form to help us.";
                Response.Redirect("calltaxi.aspx");
            }
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (this.drp_PAtown.SelectedValue == this.drp_AAtown.SelectedValue)
        {
            this.Label1.Text = "Please select different towns";
        }
        else
        {
            this.Label1.Text = "";
            if (this.txt_cptch.Text.ToUpper() == Session["Captcha"].ToString())
            {
                this.Label1.Text = "";
                int taxiToWork = 0;
                string PATown = this.drp_PAtown.SelectedValue;
                string AATown = this.drp_AAtown.SelectedValue;
                //string selectTaxi = "SELECT dbo.ConnectionFleetTown.FleetID, dbo.ConnectionFleetTown.TownID, dbo.ConnectionTaxiFleet.TaxiID, dbo.ConnectionTaxiFleet.FleetID AS Expr1, dbo.Taxi.ID,dbo.Taxi.PlateNo, dbo.Taxi.DailyKm, dbo.Taxi.TotalKm, dbo.Taxi.Revenue, dbo.Taxi.Available, dbo.Taxi.MaxKmLimit, dbo.Taxi.DayNight,dbo.Taxi.CustomerArriveTime as CustomerArriveTime, dbo.Taxi.DriverSSN, dbo.Taxi.CurrentLocation FROM dbo.ConnectionFleetTown INNER JOIN dbo.ConnectionTaxiFleet ON dbo.ConnectionFleetTown.FleetID = dbo.ConnectionTaxiFleet.FleetID INNER JOIN dbo.Taxi ON dbo.ConnectionTaxiFleet.TaxiID = dbo.Taxi.ID WHERE dbo.Taxi.Available='ok' AND dbo.Taxi.CurrentLocation ='" + PATown + "' AND dbo.ConnectionFleetTown.TownID=" + AATown;

                SqlDataSource5.SelectParameters[0].DefaultValue = PATown;
                SqlDataSource5.SelectParameters[1].DefaultValue = AATown;
                SqlDataSource5.SelectParameters[2].DefaultValue = "ok";
                DataView ds = (DataView)SqlDataSource5.Select(DataSourceSelectArguments.Empty);


                if (ds != null && ds.Table.Rows.Count > 0)
                {
                    taxiToWork = selectLeastWorked(ds);
                }
                else
                {
                    //string selectTaxi2 = "SELECT dbo.ConnectionFleetTown.FleetID, dbo.ConnectionFleetTown.TownID, dbo.ConnectionTaxiFleet.TaxiID, dbo.ConnectionTaxiFleet.FleetID AS Expr1, dbo.Taxi.ID,dbo.Taxi.PlateNo, dbo.Taxi.DailyKm, dbo.Taxi.TotalKm, dbo.Taxi.Revenue, dbo.Taxi.Available, dbo.Taxi.MaxKmLimit, dbo.Taxi.DayNight,dbo.Taxi.CustomerArriveTime as CustomerArriveTime, dbo.Taxi.DriverSSN, dbo.Taxi.CurrentLocation FROM dbo.ConnectionFleetTown INNER JOIN dbo.ConnectionTaxiFleet ON dbo.ConnectionFleetTown.FleetID = dbo.ConnectionTaxiFleet.FleetID INNER JOIN dbo.Taxi ON dbo.ConnectionTaxiFleet.TaxiID = dbo.Taxi.ID WHERE dbo.Taxi.Available='ok' AND dbo.Taxi.CurrentLocation ='" + PATown + "' AND dbo.ConnectionFleetTown.TownID=" + PATown;
                    //DataSet ds2 = DBClass.Default.SelectCommand(selectTaxi2);
                    SqlDataSource5.SelectParameters[0].DefaultValue = AATown;
                    SqlDataSource5.SelectParameters[1].DefaultValue = AATown;
                    SqlDataSource5.SelectParameters[2].DefaultValue = "ok";
                    DataView ds2 = (DataView)SqlDataSource5.Select(DataSourceSelectArguments.Empty);
                    taxiToWork = selectLeastWorked(ds2);

                }

                report = this.txt_PAadd.Text + this.drp_PAtown.SelectedItem.Text + "," + this.drp_PAcity.SelectedItem.Text + "|" + this.txt_note.Text + "|" + this.drp_AAtown.Text + " " + this.txt_AAadd.Text;
                
               
                    sendTaxi(taxiToWork, PATown, AATown);
                           }
            else
            {
                this.Label1.Text = "Security code is wrong. Please try again";
                this.txt_cptch.Text = "";
            }
        }
    }

    protected void drp_PAcity_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["SCity"] = this.drp_PAcity.SelectedValue;
    }
    
    protected void Button2_Click(object sender, EventArgs e)
    {
        setMemberAddress(true);
    }


}